//
//  ImproveInfoViewController.swift
//  YLH
//
//  Created by qinjiangtao on 2024/1/11.
//

import UIKit
import BRPickerView

class ImproveInfoViewController: QIBaseViewController {
    
    private var iconBtn = UIButton()
    private var nameTextF = UITextField()
    private var birthdayTextF = UITextField()
    private var heightTextF = UITextField()
    private var cityTextF = UITextField()
    private var emailTextF = UITextField()
    private var coverUrl = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "完善资料"
     
        addUI()
    }
    

    
    private func addUI() {
        self.view.addGradientColor(fromColors: [ColorWithStr("#FFD1D6").cgColor, ColorWithStr("#FFFFFF").cgColor, ColorWithStr("#F6F7F9").cgColor], locationArr: [0, 0.5, 1.0], with: .topToBottom)
        
        iconBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH / 2 - 50, y: NAV_HEIGHT + 40, width: 100, height: 100)
            $0.imageView?.contentMode = .scaleAspectFill
            $0.setImage(UIImage(named: "相机_登录"), for: .normal)
            $0.addRoundedCorners(withRadius: 50)
            $0.addTarget(self, action: #selector(iconBtnClick), for: .touchUpInside)
        }
        view.addSubview(iconBtn)
        
        let titleL = UILabel().then({
            $0.frame = CGRect(x: 0, y: iconBtn.bottom + 14, width: SCREEN_WIDTH, height: 20)
            $0.text = "头像"
            $0.textAlignment = .center
            $0.font = SYSFONT(ofSize: 14)
        })
        view.addSubview(titleL)
        
        nameTextF = addTextField(titleStr: "姓名", titleLY: iconBtn.bottom + 90, isRightImag: false)
        nameTextF.placeholder = "请输入您的姓名"
        
        birthdayTextF = addTextField(titleStr: "出生日期", titleLY: nameTextF.bottom + 20, isRightImag: true)
        birthdayTextF.placeholder = "请选择出生日期"
        let birthdayTap = UITapGestureRecognizer(target: self, action: #selector(birthdayTextFClick))
        birthdayTextF.addGestureRecognizer(birthdayTap)
        
        heightTextF = addTextField(titleStr: "身高", titleLY: birthdayTextF.bottom + 20, isRightImag: true)
        heightTextF.placeholder = "请选择身高"
        let heightTap = UITapGestureRecognizer(target: self, action: #selector(heightTextFClick))
        heightTextF.addGestureRecognizer(heightTap)
        
        cityTextF = addTextField(titleStr: "所在城市", titleLY: heightTextF.bottom + 20, isRightImag: true)
        cityTextF.placeholder = "请选择所在城市"
        let cityTap = UITapGestureRecognizer(target: self, action: #selector(cityTextFClick))
        cityTextF.addGestureRecognizer(cityTap)
        
        emailTextF = addTextField(titleStr: "邮箱号", titleLY: cityTextF.bottom + 20, isRightImag: false)
        emailTextF.placeholder = "请输入您的邮箱号"
        
        let nextBtn = UIButton().then {
            $0.frame = CGRect(x: 20, y: SCREEN_HEIGHT - 80, width: SCREEN_WIDTH - 40, height: 48)
            $0.backgroundColor = MainColor
            $0.titleLabel?.font = SYSFONT(ofSize: 14)
            $0.setTitle("完成", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 24)
            $0.addTarget(self, action: #selector(nextBtnClick), for: .touchUpInside)
        }
        view.addSubview(nextBtn)
    }
    
    private func addTextField(titleStr: String, titleLY: CGFloat, isRightImag: Bool) -> UITextField {
        
        let titleL = UILabel().then({
            $0.frame = CGRect(x: 16, y: titleLY, width: 60, height: 40)
            $0.text = titleStr
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 14)
        })
        view.addSubview(titleL)
        
        let leftView = UIView()
        leftView.frame = CGRect(x: 0, y: 0, width: 10, height: 0)
        let rightView = UIView()
        if isRightImag {
            rightView.frame = CGRect(x: 0, y: 0, width: 30, height: 40)
            let rightImgView = UIImageView().then {
                $0.frame = CGRect(x: 10, y: 13, width: 10, height: 14)
                $0.image = UIImage(named: "箭头右")
            }
            rightView.addSubview(rightImgView)
        }
        let TextF = UITextField().then {
            $0.frame = CGRect(x: 82, y: titleLY, width: SCREEN_WIDTH - 100, height: 40)
            $0.backgroundColor = ColorEEEEEE
            $0.font = SYSFONT(ofSize: 13)
            $0.placeholder = ""
            $0.backgroundColor = ColorEEEEEE
            $0.leftView = leftView
            $0.leftViewMode = .always
            $0.rightView = rightView
            $0.rightViewMode = .always
            $0.addRoundedCorners(withRadius: 20)
        }
        view.addSubview(TextF)
        
        
        return TextF
    }
    
    @objc private func nextBtnClick() {
        let nameStr = nameTextF.text ?? ""
        let birthdayStr = birthdayTextF.text ?? ""
        let heightStr = heightTextF.text ?? ""
        let cityStr = cityTextF.text ?? ""
        let emailStr = emailTextF.text ?? ""
        
        guard coverUrl.count > 10 else {
            ShowHUD(str: "请选择头像")
            return
        }
        guard nameStr.count > 0 else {
            ShowHUD(str: "请输入您的姓名")
            return
        }
        guard birthdayStr.count > 0 else {
            ShowHUD(str: "请选择出生日期")
            return
        }
        guard heightStr.count > 0 else {
            ShowHUD(str: "请选择身高")
            return
        }
        guard cityStr.count > 0 else {
            ShowHUD(str: "请选择所在城市")
            return
        }
        guard emailStr.count > 0 else {
            ShowHUD(str: "请输入您的邮箱号")
            return
        }
        
        let parame = [
            "nickname": nameStr,
            "avatar": coverUrl,
            "birthday": birthdayStr,
            "height": heightStr,
            "city": cityStr,
            "email": emailStr
        ]
        QINetworkManager.requestJson(urlStr: "/User/editUserInfo", parameters: parame) { json in
            print(json)
            ShowHUD(str: "登录成功!")
            Defaults[\.isLogin] = true
            
            let window = UIApplication.shared.keyWindow
            window?.switchRootCtrl()
        } fail: { json in
            let model = json.dictionaryObject?.kj.model(QIBaseModel.self) ?? QIBaseModel()
            if model.code == 106 || model.code == 107 {   //幸福感问卷调查
               let ctl = QuestionnaireSurveyViewController()
               ctl.code = model.code
               self.navigationController?.pushViewController(ctl, animated: true)
           }
        }
    }
    
    @objc private func birthdayTextFClick() {
        let dateView = BRDatePickerView()
        dateView.pickerMode = .YMD
        dateView.title = "出生日期"
        dateView.resultBlock = {selectDate, selectValue in
            print(selectValue ?? "")
            self.birthdayTextF.text = selectValue
        }
        dateView.show()
    }
    @objc private func heightTextFClick() {
        var heightArr = [String]()
        for h in 100...220 {
            heightArr.append("\(h) cm")
        }
        let stringPickerView = BRStringPickerView(pickerMode: .componentSingle)
        stringPickerView.title = "身高"
        stringPickerView.dataSourceArr = heightArr
        stringPickerView.selectIndex = 70
        stringPickerView.resultModelBlock = {resultModel in
            print(resultModel?.value ?? "")
            self.heightTextF.text = resultModel?.value
        }
        stringPickerView.show()
    }
    @objc private func cityTextFClick() {
        let addressPickerView = BRAddressPickerView(pickerMode: .area)
        addressPickerView.title = "请选择所在地区"
        addressPickerView.resultBlock = { province, city, area in
            let addressStr = "\(province?.name ?? "")/\(city?.name ?? "")/\(area?.name ?? "")"
            print(addressStr)
            self.cityTextF.text = addressStr
        }
        addressPickerView.show()
    }
    
    @objc private func iconBtnClick() {
        let alertCtl = UIAlertController(title: "选项", message: "", preferredStyle: .actionSheet)
        alertCtl.addAction(UIAlertAction(title: "拍照", style: .default, handler: { (_) in
            let imagePickerCtl = UIImagePickerController()
            imagePickerCtl.delegate = self
            imagePickerCtl.allowsEditing = true
            imagePickerCtl.sourceType = .camera
            self.present(imagePickerCtl, animated: true)
        }))
        alertCtl.addAction(UIAlertAction(title: "从手机相册选择", style: .default, handler: { (_) in
            let imagePickerCtl = UIImagePickerController()
            imagePickerCtl.delegate = self
            imagePickerCtl.allowsEditing = true
            imagePickerCtl.sourceType = .savedPhotosAlbum
            self.present(imagePickerCtl, animated: true)
        }))
        alertCtl.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
            
        }))
        self.present(alertCtl, animated: true)
    }
    

}



extension ImproveInfoViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let image: UIImage = info[UIImagePickerController.InfoKey.editedImage] as! UIImage
        iconBtn.setImage(image, for: .normal)
        updateImage(img: image)
        picker.dismiss(animated: true)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true)
    }
    private func updateImage(img: UIImage) {
        QINetworkManager.uploadImage(urlStr: "", image: img, success: { json in
            print(json)
            self.coverUrl = "\(json["url"] ?? "")"
        })
    }
    
}
